export const storageConfig = {
  type: "localStorage", // localStorage sessionStorage uniStorage
  expire: 100000, //过期时间 秒
};
// 设置 setStorage
export const setStorage = (key, data, expire = 0) => {
  if (data === "" || data === null || data === undefined) {
    data = null;
  }
  if (isNaN(expire)) throw new Error("Expire must be a number");
  expire = (expire ? expire : storageConfig.expire) * 60000;
  let res = {
    data,
    time: Date.now(),
    expire: storageConfig.expire,
  };
  switch (storageConfig.type) {
    case "uniStorage":
      uni.setStorageSync(key, res);
      break;
    default:
      window[storageConfig.type].setItem(key, JSON.stringify(res));
      break;
  }
  preserveKey(key);
};
// 获取 getStorage
export const getStorage = (key) => {
  if (!hasStorage(key)) return null;
  let storage =
    storageConfig.type === "uniStorage"
      ? uni.getStorageSync(key)
      : JSON.parse(window[storageConfig.type].getItem(key));
  let time = Date.now();
  if (storage.expire && storageConfig.expire * 1000 < time - storage.time) {
    removeStorage(key);
    return null;
  } else {
    setStorage(key, storage.data);
    return storage.data;
  }
};
// 是否存在 hasStorage
export const hasStorage = (key) => {
  let keyList = JSON.parse(window[storageConfig.type].getItem("preserveKey"));
  if (
    keyList &&
    keyList.includes(key) &&
    JSON.parse(window[storageConfig.type].getItem(key))
  )
    return true;
  else return false;
};
// 获取所有key getStorageKeys
export const getStorageKeys = () => {
  return [
    ...new Set(
      storageConfig.type === "uniStorage"
        ? uni.getStorageSync("preserveKey")
        : JSON.parse(window[storageConfig.type].getItem("preserveKey"))
    ),
  ];
};
// 获取localStorage长度 getStorageLength
export const getStorageLength = () => {
  return getStorageKeys().length;
};
// 获取全部 getAllStorage
export const getAllStorage = () => {
  let keyList = getStorageKeys();
  let storageAll = {};
  keyList.forEach((ele) => {
    storageAll[ele] = getStorage(ele);
  });
  return storageAll;
};
// 删除 removeStorage
export const removeStorage = (key) => {
  switch (storageConfig.type) {
    case "uniStorage":
      uni.removeStorageSync(key);
      break;
    default:
      window[storageConfig.type].removeItem(key);
      break;
  }
};
// 清空 clearStorage
export const clearStorage = () => {
  switch (storageConfig.type) {
    case "uniStorage":
      uni.clearStorageSync();
      break;
    default:
      window[storageConfig.type].clear();
      break;
  }
};
// 保存key
const preserveKey = (key) => {
  let keyList = getStorageKeys();
  if (!keyList.includes(key)) {
    keyList.push(key);
    switch (storageConfig.type) {
      case "uniStorage":
        uni.setStorageSync("preserveKey", keyList);
        break;
      default:
        window[storageConfig.type].setItem(
          "preserveKey",
          JSON.stringify(keyList)
        );
        break;
    }
  }
};
